package com.member.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.CollectorUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.shop.domain.*;
import com.member.shop.dto.SysBizMarketPageDto;
import com.member.shop.dto.SysBizSaleActivityDto;
import com.member.shop.mapper.*;
import com.member.shop.service.ISysBizCouponReceiveService;
import com.member.shop.service.ISysBizMarketPageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 营销页面定义Service业务层处理
 *
 * @author lixinchen
 * @date 2025-02-14
 */
@Service
public class SysBizMarketPageServiceImpl extends ServiceImpl<SysBizMarketPageMapper, SysBizMarketPage> implements ISysBizMarketPageService {
    @Resource
    private SysBizMarketPageMapper sysBizMarketPageMapper;

    @Resource
    private SysBizMarketPageCategoryMapper sysBizMarketPageCategoryMapper;


    @Resource
    private SysBizCouponMapper sysBizCouponMapper;


    @Resource
    private SysBizGoodsSkuMapper sysBizGoodsSkuMapper;


    @Resource
    private SysBizGoodsMapper sysBizGoodsMapper;

    @Resource
    private ISysBizCouponReceiveService sysBizCouponReceiveService;
    /**
     * 查询营销页面定义
     *
     * @param id 营销页面定义主键
     * @return 营销页面定义
     */
    @Override
    public SysBizMarketPage selectSysBizMarketPageById(Long id) {
        return sysBizMarketPageMapper.selectById(id);
    }

    /**
     * 查询营销页面定义列表
     *
     * @param queryWrapper 营销页面定义
     * @return 营销页面定义
     */
    @Override
    public List<SysBizMarketPage> selectSysBizMarketPageList(LambdaQueryWrapper<SysBizMarketPage> queryWrapper) {
        return sysBizMarketPageMapper.selectList(queryWrapper);
    }

    /**
     * 查询营销页面定义列表
     *
     * @param sysBizMarketPage 营销页面定义
     * @return 营销页面定义
     */
    @Override
    public List<SysBizMarketPage> selectSysBizMarketPageList(SysBizMarketPage sysBizMarketPage) {
        return sysBizMarketPageMapper.selectSysBizMarketPageList(sysBizMarketPage);
    }

    /**
     * 新增营销页面定义
     *
     * @param sysBizMarketPage 营销页面定义
     * @return 结果
     */
    @Override
    public int insertSysBizMarketPage(SysBizMarketPage sysBizMarketPage) {
        sysBizMarketPage.setCreateTime(DateUtils.getNowDate());
        return sysBizMarketPageMapper.insert(sysBizMarketPage);
    }

    /**
     * 修改营销页面定义
     *
     * @param sysBizMarketPage 营销页面定义
     * @return 结果
     */
    @Override
    public int updateSysBizMarketPage(SysBizMarketPage sysBizMarketPage) {
        sysBizMarketPage.setUpdateTime(DateUtils.getNowDate());
        return sysBizMarketPageMapper.updateById(sysBizMarketPage);
    }

    /**
     * 批量删除营销页面定义
     *
     * @param ids 需要删除的营销页面定义主键
     * @return 结果
     */
    @Override
    public int deleteSysBizMarketPageByIds(Long[] ids) {
        return sysBizMarketPageMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除营销页面定义信息
     *
     * @param id 营销页面定义主键
     * @return 结果
     */
    @Override
    public int deleteSysBizMarketPageById(Long id) {
        SysBizMarketPage sysBizMarketPage = new SysBizMarketPage();
        sysBizMarketPage.setId(id);
        sysBizMarketPage.setDeleted(OrderDeleteEnum.DELETE.getKey());
        return sysBizMarketPageMapper.updateById(sysBizMarketPage);
    }

    @Override
    public SysBizMarketPageDto queryMarketPage(Long id, Long tenantId ,Long userId) {

        SysBizMarketPageDto sysBizMarketPageDto = new SysBizMarketPageDto();
        SysBizMarketPage sysBizMarketPage = sysBizMarketPageMapper.selectById(id);
        BeanUtil.copyProperties(sysBizMarketPage, sysBizMarketPageDto);

        //优惠券
        if (StringUtils.isNotBlank(sysBizMarketPage.getCategoryCouponId())) {
            // 假设 sysBizMarketPage.getCategoryCouponId() 返回一个逗号分隔的字符串
            String[] split = sysBizMarketPage.getCategoryCouponId().split(",");
            // 使用 Stream API 将 String[] 转换成 List<Long>
            List<Long> categoryCouponIdList = Arrays.stream(split)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            List<SysBizMarketPageCategory> sysBizMarketPageCategories = sysBizMarketPageCategoryMapper.selectList(
                    new LambdaQueryWrapper<SysBizMarketPageCategory>()
                            .in(SysBizMarketPageCategory::getId, categoryCouponIdList));
            if (!CollectionUtils.isEmpty(sysBizMarketPageCategories)) {
                for (SysBizMarketPageCategory sysBizMarketPageCategory : sysBizMarketPageCategories) {
                    if (StringUtils.isNotBlank(sysBizMarketPageCategory.getCouponId())) {
                        String[] split2 = sysBizMarketPageCategory.getCouponId().split(",");
                        // 使用 Stream API 将 String[] 转换成 List<Long>
                        List<Long> categoryCouponIdList2 = Arrays.stream(split2)
                                .map(Long::parseLong)
                                .collect(Collectors.toList());
                        List<SysBizCoupon> sysBizCoupons = sysBizCouponMapper.selectList(new LambdaQueryWrapper<SysBizCoupon>()
                                .in(SysBizCoupon::getId, categoryCouponIdList2));
                        for (SysBizCoupon sysBizCoupon : sysBizCoupons) {
                            LambdaQueryWrapper<SysBizCouponReceive> receiveLambdaQueryWrapper = new LambdaQueryWrapper<>(

                            );
                            receiveLambdaQueryWrapper.eq(SysBizCouponReceive::getUserId, userId);
                            receiveLambdaQueryWrapper.eq(SysBizCouponReceive::getCouponId, sysBizCoupon.getId());
                            List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.list(receiveLambdaQueryWrapper);
//                            if (!CollectionUtils.isEmpty(sysBizCouponReceives) && sysBizCouponReceives.size() >= sysBizCoupon.getUserLimit()) {
                            if (!CollectionUtils.isEmpty(sysBizCouponReceives)) {
                                sysBizCoupon.setReceiveStatus(1);
                            }else {
                                sysBizCoupon.setReceiveStatus(0);
                            }
                        }
                        sysBizMarketPageCategory.setCouponList(sysBizCoupons);

                    }
                }
                sysBizMarketPageDto.setCategoryCouponList(sysBizMarketPageCategories);
            }

        }


        //商品
        if (StringUtils.isNotBlank(sysBizMarketPage.getCategoryGoodsId())) {
            // 假设 sysBizMarketPage.getCategoryCouponId() 返回一个逗号分隔的字符串
            String[] split = sysBizMarketPage.getCategoryGoodsId().split(",");
            // 使用 Stream API 将 String[] 转换成 List<Long>
            List<Long> categoryGoodsIdList = Arrays.stream(split)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            List<SysBizMarketPageCategory> sysBizMarketPageCategories = sysBizMarketPageCategoryMapper.selectList(
                    new LambdaQueryWrapper<SysBizMarketPageCategory>()
                            .in(SysBizMarketPageCategory::getId, categoryGoodsIdList));

            sysBizMarketPageCategories.sort(Comparator.comparing(SysBizMarketPageCategory::getActivityType));

            if (!CollectionUtils.isEmpty(sysBizMarketPageCategories)) {
                    for (SysBizMarketPageCategory sysBizMarketPageCategory : sysBizMarketPageCategories) {
                        if (StringUtils.isNotBlank(sysBizMarketPageCategory.getGoodsId())) {
                            String[] split2 = sysBizMarketPageCategory.getGoodsId().split(",");
                            // 使用 Stream API 将 String[] 转换成 List<Long>
                            List<Long> categorGoodsList2 = Arrays.stream(split2)
                                    .map(Long::parseLong)
                                    .collect(Collectors.toList());
                            List<SysBizGoodsSku> sysBizGoodsSkuList = sysBizGoodsSkuMapper.selectList(new LambdaQueryWrapper<SysBizGoodsSku>()
                                    .in(SysBizGoodsSku::getId, categorGoodsList2));
                            for (SysBizGoodsSku sysBizGoodsSku : sysBizGoodsSkuList) {
                                Long goodsId = sysBizGoodsSku.getGoodsId();
                                SysBizGoods sysBizGoods = sysBizGoodsMapper.selectSysBizGoodsById(goodsId);
                                if(sysBizGoods != null){
                                    sysBizGoodsSku.setGoodsName(sysBizGoods.getName());
                                }
                            }
                            sysBizMarketPageCategory.setGoodsList(sysBizGoodsSkuList);
                        }
                    }
                sysBizMarketPageDto.setCategoryGoodsList(sysBizMarketPageCategories);
            }
        }

        return sysBizMarketPageDto;
    }

    @Override
    public SysBizSaleActivityDto saleActivity(Long tenantId) {

        List<SysBizMarketPage> sysBizMarketPage =  sysBizMarketPageMapper.selectByTenantId(tenantId);
        List<SysBizMarketPageCategory> sysBizMarketPageCategories = sysBizMarketPageCategoryMapper.selectList(
                new LambdaQueryWrapper<SysBizMarketPageCategory>()
                .eq(SysBizMarketPageCategory::getActivityType, 1)
                .eq(SysBizMarketPageCategory::getDisplayed, EnableStatusEnum.ENABLE.getKey()));

        if (!CollectionUtils.isEmpty(sysBizMarketPageCategories)) {
            List<Long> categoryIds = sysBizMarketPageCategories.stream()
                    .map(SysBizMarketPageCategory::getId)
                    .collect(Collectors.toList());

            for (SysBizMarketPage sysBizMarketPage1 : sysBizMarketPage) {
                if (sysBizMarketPage1.getCategoryGoodsId() != null && !sysBizMarketPage1.getCategoryGoodsId().isEmpty()) {
                    List<Long> categoryGoodsIds = Arrays.stream(sysBizMarketPage1.getCategoryGoodsId().split(","))
                            .map(Long::parseLong)
                            .collect(Collectors.toList());

                    for (Long categoryId : categoryGoodsIds) {
                        if (categoryIds.contains(categoryId)) {
                            // 找到匹配的 ID
                            System.out.println("Found matching category ID: " + categoryId);
                            // 在这里可以添加其他逻辑
                            SysBizSaleActivityDto sysBizSaleActivityDto = new SysBizSaleActivityDto();
                            SysBizMarketPageCategory sysBizMarketPageCategory = sysBizMarketPageCategoryMapper.selectSysBizMarketPageCategoryById(categoryId);
                            if(sysBizMarketPageCategory.getActivityStartTime().getTime() >= new Date().getTime()){
                                continue;
                            }

                            if(sysBizMarketPageCategory.getActivityEndTime().getTime() <= new Date().getTime()){
                                continue;
                            }

                            sysBizSaleActivityDto.setId(sysBizMarketPageCategory.getId());
                            sysBizSaleActivityDto.setActivityStartTime(sysBizMarketPageCategory.getActivityStartTime());
                            sysBizSaleActivityDto.setActivityEndTime(sysBizMarketPageCategory.getActivityEndTime());

                            String[] split2 = sysBizMarketPageCategory.getGoodsId().split(",");
                            // 使用 Stream API 将 String[] 转换成 List<Long>
                            List<Long> categorGoodsList2 = Arrays.stream(split2)
                                    .map(Long::parseLong)
                                    .collect(Collectors.toList());

                            List<SysBizGoodsSku> sysBizGoodsSkuList = sysBizGoodsSkuMapper.selectList(new LambdaQueryWrapper<SysBizGoodsSku>()
                                    .in(SysBizGoodsSku::getId, categorGoodsList2));
                            for (SysBizGoodsSku sysBizGoodsSku : sysBizGoodsSkuList) {
                                Long goodsId = sysBizGoodsSku.getGoodsId();
                                SysBizGoods sysBizGoods = sysBizGoodsMapper.selectSysBizGoodsById(goodsId);
                                if(sysBizGoods != null){
                                    sysBizGoodsSku.setGoodsName(sysBizGoods.getName());
                                }
                            }
                            sysBizSaleActivityDto.setMarketId(sysBizMarketPage1.getId());
                            sysBizSaleActivityDto.setGoodsList(sysBizGoodsSkuList);
                            return sysBizSaleActivityDto;
                        }
                    }
                }
            }
        }

        return null;
    }
}
